package io.demo.message.domain.proto;

import io.demo.message.domain.Country.CountryBuilder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CountryMessageConverter
    implements MessageConverter<io.demo.message.domain.Country, Country> {

  @Override
  public Country toMessage(io.demo.message.domain.Country pojo) {
    City capital =
        MessageConverters.toMessage(pojo.getCapitalCity(), io.demo.message.domain.City.class);

    Country.Builder country = Country.newBuilder()
        .setCapitalCity(capital)
        .setId(pojo.getId())
        .setName(pojo.getName());

    if (pojo.getEthnics() == null) {
      pojo.setEthnics(null);
    } else if (pojo.getEthnics().isEmpty()) {
      country.addAllEthnics(Collections.emptyList());
    } else {
      pojo.getEthnics().forEach(e -> {
        Ethnic ee = MessageConverters.toMessage(e, io.demo.message.domain.Ethnic.class);
        country.addEthnics(ee);
      });
    }

    return country
        .build();
  }

  @Override
  public io.demo.message.domain.Country fromMessage(Country message) {
    CountryBuilder countryBuilder = io.demo.message.domain.Country.builder()
        .id(message.getId())
        .name(message.getName())
        .capitalCity(MessageConverters
            .fromMessage(message.getCapitalCity(), io.demo.message.domain.City.class));

    if (message.getEthnicsList() == null) {
      countryBuilder.ethnics(null);
    } else if (message.getEthnicsList().isEmpty()) {
      countryBuilder.ethnics(Collections.emptyList());
    } else {
      List<io.demo.message.domain.Ethnic> list = new ArrayList<>();
      message.getEthnicsList().forEach(ee ->
          list.add(MessageConverters.fromMessage(ee, io.demo.message.domain.Ethnic.class)));
      countryBuilder.ethnics(list);
    }

    return countryBuilder.build();
  }
}
